package com.zbbt.sportslottery.ui.activity;

import java.util.regex.Pattern;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.gc.materialdesign.views.ButtonRectangle;
import com.gc.materialdesign.views.ProgressBarCircularIndetermininate;
import com.google.gson.JsonObject;
import com.zbbt.sportslottery.R;
import com.zbbt.sportslottery.app.App;
import com.zbbt.sportslottery.app.Constant;
import com.zbbt.sportslottery.app.ServerConfig;
import com.zbbt.sportslottery.bean.UserInfo;
import com.zbbt.sportslottery.net.TypeGsonHttpHandler;
import com.zbbt.sportslottery.net.TypeResultHttpHandler;
import com.zbbt.sportslottery.net.ZbHttpClient;
import com.zbbt.sportslottery.ui.widget.ClearEditText;
import com.zbbt.sportslottery.util.DataValidator;
import com.zbbt.sportslottery.util.KeyUtil;
import com.zbbt.sportslottery.util.LogUtil;
import com.zbbt.sportslottery.util.Md5;
import com.zbbt.sportslottery.util.SharePreferUtil;
import com.zbbt.sportslottery.util.ToastUtil;
import com.zbbt.sportslottery.util.UmengUtil;
import com.zbbt.sportslottery.util.ViewUtil;

/**
 * 
 * @ClassName: RegisterActivity
 * @Description: 注册
 * @author：GaomingShuo
 * @date：2015-3-3 下午2:36:20
 * @version V1.0
 */
public class RegisterActivity extends SimpleBaseActivity {
	private ClearEditText userName;
	private ClearEditText userPassword;
	private ClearEditText etCodeText;
	private ButtonRectangle registerButton;
	private ButtonRectangle btnRectangle;
	private CheckBox checkbox;
	private TextView serviceTerm;
	private String usernameContent;
	private String passwordContent;
	private String codeContent;
	private View mRootview;
	private LinearLayout linearLayoutImg1;
	private ProgressBarCircularIndetermininate mProgressBar;
	boolean isHttp = true;// 是否执行完一次网络连接

	@Override
	protected void onActivityCreated(Bundle savedInstanceState) {
		setContentView(R.layout.activity_register);
	}

	@Override
	protected void initView() {
		mProgressBar = (ProgressBarCircularIndetermininate) findViewById(R.id.mProgressBar);
		userName = (ClearEditText) findViewById(R.id.username_edittext_register);
		userPassword = (ClearEditText) findViewById(R.id.password_edittext_register);
		registerButton = (ButtonRectangle) findViewById(R.id.register_button);
		registerButton.setTextColor(getResources().getColor(R.color.white));
		btnRectangle = (ButtonRectangle) findViewById(R.id.btn_speech);
		btnRectangle.setTextSize(17);// 控制语音获取文字的大小
		btnRectangle.setTextColor(getResources().getColor(R.color.white));
		linearLayoutImg1 = (LinearLayout) findViewById(R.id.ll_img);
		registerButton.setTextSize(20);
		serviceTerm = (TextView) findViewById(R.id.serviceTerm);
		checkbox = (CheckBox) findViewById(R.id.register_checkBox);
//		checkbox.setMinimumWidthAndHeight(20, 20);// 设置对勾的背景大小
//		checkbox.setCheckColor(getResources(), R.drawable.sprite_check_grey);// 设置对勾的背景颜色
//		checkbox.setBackgroundFrame(R.drawable.check_selected_press_bg);//设置自定义框体
		mRootview = findViewById(R.id.mRootview);
		ViewUtil.listenerSoftInput(linearLayoutImg1, mRootview);
		userName.addTextChangedListener(mTextWatcher);
		etCodeText = (ClearEditText) findViewById(R.id.et_code);
	}

	TextWatcher mTextWatcher = new TextWatcher() {
		@Override
		public void onTextChanged(CharSequence s, int start, int before, int count) {
			final String s1 = userName.getText().toString();
			if (!s1.equals("")) {
				if (!Pattern.matches("^[a-zA-Z0-9\u4e00-\u9fa5]+$", s1)) {
					userName.setText("");
					userName.setShakeAnimation();
					ToastUtil.showLong("用户名只能包含数字");
				}
			}
		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

		@Override
		public void afterTextChanged(Editable s) {

		}
	};

	@Override
	protected void setListener() {
		serviceTerm.setOnClickListener(this);
		registerButton.setOnClickListener(this);
		btnRectangle.setOnClickListener(this);
		userPassword.setOnClickListener(this);

	}

	@Override
	protected void initData() {

	}

	@Override
	protected void onClickEvent(View v) {
		switch (v.getId()) {
		case R.id.serviceTerm:
			Intent i = new Intent(RegisterActivity.this, GameDataActivity.class);
			i.putExtra("Url", "http://123.57.14.225/zgtcb/html/wanfajieshao/2015/1125/7680.html");
			i.putExtra("Title", "用户协议");
			i.putExtra("ShowShare", false);
			startActivity(i);
			break;
		case R.id.btn_speech:
			requestCodeTask();// 获取验证码按钮
			break;
		case R.id.register_button:
			registeronClick();// 确认注册按钮
			break;
		default:
			break;
		}
	}

	// xml设置了点击的效果 确认注册按钮
	public void registeronClick() {
		usernameContent = userName.getText().toString();
		passwordContent = userPassword.getText().toString();
		codeContent = etCodeText.getText().toString();
		LogUtil.printI(TAG, "账号" + usernameContent + "====密码" + passwordContent);

		if (!checkbox.isChecked()) {
			ToastUtil.showShort("请阅读并同意'服务条款'");
			return;
		}

		if (TextUtils.isEmpty(usernameContent)) {
			ToastUtil.showLong("账号不能为空");
			userName.setShakeAnimation();
			return;
		}
		if (usernameContent.length() < 6 || usernameContent.length() > 16) {
			ToastUtil.showLong("您输入的账号应在6~16个字符");
			userName.setShakeAnimation();
			return;
		}
		if (TextUtils.isEmpty(passwordContent)) {
			ToastUtil.showLong("密码不能为空");
			userPassword.setShakeAnimation();
			return;
		}
		if (passwordContent.length() > 16 || passwordContent.length() < 6) {
			ToastUtil.showLong("您输入的密码应在6~16个字符");
			userPassword.setShakeAnimation();
			return;
		}
		if (TextUtils.isEmpty(codeContent)) {
			ToastUtil.showShort("验证码不能为空");
			etCodeText.setShakeAnimation();
			return;
		}
		if (isHttp) {
			httpData(usernameContent, passwordContent);
		}

	}

	/**
	 * 
	 * @MethodName:httpData
	 * @Description: 语音验证获取验证码
	 * @author：GaomingShuo
	 * @date：2015-3-2 下午4:55:32
	 * @param usernameContent
	 * @param passwordContent
	 *            void
	 */
	private void requestCodeTask() {
		usernameContent = userName.getText().toString().trim();
		if (TextUtils.isEmpty(usernameContent)) {
			ToastUtil.showLong("手机号不能为空");
			userName.setShakeAnimation();// 震动
			return;
		}
		if (!DataValidator.isMobile(usernameContent)) {
			ToastUtil.showLong("请输入正确的手机号");
			userName.setShakeAnimation();
			return;
		}
		isPhoneNumber(usernameContent);
	}

	public void http() {
		mProgressBar.setVisibility(View.VISIBLE);
		downTimer.start();
		JsonObject jsonObject = new JsonObject();
		jsonObject.addProperty("mobile", usernameContent);
		ZbHttpClient.postNewApi(ServerConfig.API_REGISTER_GETCODE, jsonObject, new TypeResultHttpHandler() {

			@Override
			public void onSuccess() {
				mProgressBar.setVisibility(View.GONE);
				ToastUtil.showLong("验证码获取成功,5分钟内有效,请等待客服电话告知");
			}

			@Override
			public void onFailure(String errorCode, String errorMsg) {
				mProgressBar.setVisibility(View.GONE);
				downTimer.cancel();
				btnRectangle.setText("重新获取");
				btnRectangle.setEnabled(true);
			}
		});
	}

	/**
	 * 
	 * @MethodName:httpData
	 * @Description: 倒计时60秒
	 * @author：GaomingShuo
	 * @date：2015-3-2 下午5:07:20
	 * @param usernameContent
	 * @param passwordContent
	 *            void
	 */

	CountDownTimer downTimer = new CountDownTimer(60000, 1000) {

		@Override
		public void onTick(long millisUntilFinished) {
			btnRectangle.setText("" + millisUntilFinished / 1000);
			btnRectangle.setEnabled(false);
		}

		@Override
		public void onFinish() {
			btnRectangle.setText("重新获取");
			btnRectangle.setEnabled(true);
		}
	};

	private void httpData(final String usernameContent, final String passwordContent) {
		isHttp = false;
		mProgressBar.setVisibility(View.VISIBLE);
		JsonObject jsonObject = new JsonObject();
		jsonObject.addProperty("mobile", usernameContent);
		jsonObject.addProperty("password", Md5.getMD5(passwordContent));
		jsonObject.addProperty("checkCode", etCodeText.getText().toString());
		jsonObject.addProperty("activityId", 12);
		ZbHttpClient.postNewApi(ServerConfig.API_REGISTER, jsonObject, new TypeGsonHttpHandler<UserInfo>() {

			@Override
			public void onSuccess(UserInfo data) {
				mProgressBar.setVisibility(View.GONE);
				if (data != null) {
					UmengUtil.onEvent(context, Constant.UMENG_PERSON_REGIST);
					Intent intent = new Intent(Constant.INTENT_ACTION_LOGIN_SUCCESS);
					sendBroadcast(intent);
					ToastUtil.showLong("注册成功");
				}
				// 确认保存getUserType==2代表客户 1为店主
				SharePreferUtil.putString(Constant.USER_NAME, usernameContent);
				SharePreferUtil.putString(Constant.PASSWORD, passwordContent);
				SharePreferUtil.putString(Constant.USER_ID, data.getUserId());
				SharePreferUtil.putString(Constant.USER_TYPE, data.getUserType() + "");
				SharePreferUtil.putString(Constant.USER_SCORE, data.getTotalSource() + "");
				SharePreferUtil.putString(Constant.USER_PHOTO_IMG, data.getAvatar() + "");
				App.isLogin = true;
				isHttp = true;
				Intent intent = new Intent(context, MainActivity.class);
				intent.putExtra(KeyUtil.GotoType, KeyUtil.GOTO_FRAGMENT);
				intent.putExtra(KeyUtil.FragmentKey, KeyUtil.FRAGMENT_USERCENTER + "");
				startActivity(intent);
			}

			@Override
			public void onFailure(String errorCode, String errorMsg) {
				ToastUtil.showLong(errorMsg);
				mProgressBar.setVisibility(View.GONE);
				isHttp = true;
			}
		});
	}

	// 手机号是否存在
	private void isPhoneNumber(String usernameContent) {
		JsonObject jsonObject = new JsonObject();
		jsonObject.addProperty("mobile", usernameContent);
		ZbHttpClient.postNewApi(ServerConfig.API_ISPHONENUMBER, jsonObject, new TypeResultHttpHandler() {

			@Override
			public void onSuccess() {
				http();
			}

			@Override
			public void onFailure(String errorCode, String errorMsg) {
				mProgressBar.setVisibility(View.GONE);
				downTimer.cancel();
				btnRectangle.setText("重新获取");
				btnRectangle.setEnabled(true);
				ToastUtil.showShort(errorMsg);
				userName.setShakeAnimation();
			}
		});

	}
}